<template>
  <ContentDetailWrap
    :title="t('inventory.conversion.title')"
    @back="push('/inventory/inventory-management')"
    :class="isMobile ? 'mobile-conversion-wrap' : ''"
  >
    <template #header>
      <BaseButton @click="go(-1)">{{ t('common.back') }}</BaseButton>
      <BaseButton type="primary" :loading="loading" @click="handleSubmit(formRef)"
        >{{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    form-->
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      :label-width="isMobile ? '110px' : '110px'"
    >
      <!-- 移动端单列布局 -->
      <div v-if="isMobile" class="mobile-form-layout">
        <el-form-item :label="t('inventory.conversion.shopName')">
          <el-input v-model="form.cname" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.hashRate')">
          <el-input v-model="form.hashrate" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.warehouse')">
          <el-input v-model="form.warehouse_value" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.source')">
          <el-input v-model="form.source_table" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.arrivalDate')">
          <el-input v-model="form.arrival_date" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.shopCode')">
          <el-input v-model="form.code" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.real_arrival_date')">
          <el-input v-model="form.real_arrival_date" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.shopType')">
          <el-input v-model="form.is_futures_value" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.initialQuantity')">
          <el-input v-model="form.initial_qty" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.inboundBatches')">
          <el-input v-model="form.inbound_batch" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.numberTransfers')">
          <el-input v-model="form.convertible_qty" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.availableQuantity')">
          <el-input v-model="form.available_qty" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.sellable')">
          <el-input v-model="form.is_sale" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.lockedQuantity')">
          <el-input v-model="form.lock_qty" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.createdBy')">
          <el-input v-model="form.creator_value" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.updater')">
          <el-input v-model="form.updater_value" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.createTime')">
          <el-input v-model="form.create_time" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.updateTime')">
          <el-input v-model="form.update_time" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.finalStockTakingTime')">
          <el-input v-model="form.last_audit_date" placeholder=" " disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.costPrice')" prop="cost">
          <el-input v-model="form.cost" disabled />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.transferableType')" prop="conversionType">
          <el-select
            v-model="form.conversionType"
            :placeholder="t('inventory.conversion.conversionTypeValidation')"
            style="width: 100%"
          >
            <el-option
              v-for="item in conversionTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('inventory.conversion.intoWarehouse')"
          prop="intoWarehouse"
          v-if="form.is_futures === 2 || has_first_warehouse == 1"
        >
          <el-select
            v-model="form.intoWarehouse"
            :placeholder="t('inventory.conversion.intoWarehouseValidation')"
            @change="handleChangeIntoWarehouse"
            style="width: 100%"
          >
            <el-option
              v-for="item in form.warehouse_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('inventory.conversion.arrivalDate')"
          prop="arrivalDate"
          v-if="form.conversionType === 1"
        >
          <el-date-picker
            v-model="form.arrivalDate"
            type="date"
            style="width: 100%"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            :placeholder="t('inventory.conversion.arrivalDateValidation')"
          />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.inboundBatches')" prop="arrival_batch">
          <el-input v-model="form.arrival_batch" :placeholder="t('purchase.batchValMsg')" />
        </el-form-item>
        <el-form-item :label="t('inventory.conversion.numberConversions')" prop="conversionsNum">
          <el-input
            v-model="form.conversionsNum"
            type="number"
            :placeholder="t('inventory.conversion.conversionsNumValidation')"
          />
        </el-form-item>
      </div>

      <!-- 桌面端双列布局 -->
      <div v-else class="flex justify-between">
        <div class="w-50%">
          <el-form-item :label="t('inventory.conversion.shopName')">
            <el-input v-model="form.cname" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.warehouse')">
            <el-input v-model="form.warehouse_value" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.arrivalDate')">
            <el-input v-model="form.arrival_date" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.real_arrival_date')">
            <el-input v-model="form.real_arrival_date" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.initialQuantity')">
            <el-input v-model="form.initial_qty" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.numberTransfers')">
            <el-input v-model="form.convertible_qty" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.sellable')">
            <el-input v-model="form.is_sale" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.createdBy')">
            <el-input v-model="form.creator_value" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.createTime')">
            <el-input v-model="form.create_time" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.finalStockTakingTime')">
            <el-input v-model="form.last_audit_date" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.transferableType')" prop="conversionType">
            <el-select
              v-model="form.conversionType"
              :placeholder="t('inventory.conversion.conversionTypeValidation')"
            >
              <el-option
                v-for="item in conversionTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="t('inventory.conversion.intoWarehouse')"
            prop="intoWarehouse"
            v-if="form.is_futures === 2 || has_first_warehouse == 1"
          >
            <el-select
              v-model="form.intoWarehouse"
              :placeholder="t('inventory.conversion.intoWarehouseValidation')"
              @change="handleChangeIntoWarehouse"
            >
              <el-option
                v-for="item in form.warehouse_list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="t('inventory.conversion.arrivalDate')"
            prop="arrivalDate"
            v-if="form.conversionType === 1"
          >
            <el-date-picker
              v-model="form.arrivalDate"
              type="date"
              style="width: 100%"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD"
              :placeholder="t('inventory.conversion.arrivalDateValidation')"
            />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.inboundBatches')" prop="arrival_batch">
            <el-input v-model="form.arrival_batch" :placeholder="t('purchase.batchValMsg')" />
          </el-form-item>
        </div>
        <div class="w-50%">
          <el-form-item :label="t('inventory.conversion.hashRate')">
            <el-input v-model="form.hashrate" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.source')">
            <el-input v-model="form.source_table" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.shopCode')">
            <el-input v-model="form.code" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.shopType')">
            <el-input v-model="form.is_futures_value" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.inboundBatches')">
            <el-input v-model="form.inbound_batch" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.availableQuantity')">
            <el-input v-model="form.available_qty" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.lockedQuantity')">
            <el-input v-model="form.lock_qty" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.updater')">
            <el-input v-model="form.updater_value" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.updateTime')">
            <el-input v-model="form.update_time" placeholder=" " disabled />
          </el-form-item>
          <el-form-item :label="t('inventory.conversion.costPrice')" prop="cost">
            <el-input v-model="form.cost" disabled />
          </el-form-item>
          <el-form-item
            :label="t('inventory.conversion.numberConversions')"
            prop="conversionsNum"
            class="w-full"
          >
            <!-- <el-input
              v-model="form.conversionsNum"
              type="number"
              :placeholder="t('inventory.conversion.conversionsNumValidation')"
            /> -->
            <el-input-number
              v-model="form.conversionsNum"
              :min="1"
              :max="999999"
              :step="1"
              integer
              :precision="0"
              :placeholder="t('inventory.conversion.conversionsNumValidation')"
              class="!w-full !inline-block"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!--      table-->
    <el-table
      :data="tableData"
      ref="multipleTable"
      border
      class="m-t-10"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="order_no"
        :label="t('inventory.conversion.orderNumber')"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-button type="text" @click="handleJumpToOrder(scope.row)">{{
            scope.row.order_no
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="order_type"
        :label="t('inventory.conversion.typeOrder')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="create_time"
        :label="t('inventory.conversion.dateOrder')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="username"
        :label="t('inventory.conversion.userWhoPlacedOrder')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="total_amount"
        :label="t('inventory.conversion.amountOrder')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="pay_status"
        :label="t('inventory.conversion.paymentStatus')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="warehouse_name"
        :label="t('inventory.conversion.warehouse')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="product_name"
        :label="t('inventory.conversion.shop')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="num"
        :label="t('inventory.conversion.quantityPurchased')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="original_price"
        :label="t('inventory.conversion.originalPrice')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="actual_price"
        :label="t('inventory.conversion.actualAmountPaid')"
        :show-overflow-tooltip="true"
      />
    </el-table>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import type { FormInstance, FormRules, TableInstance } from 'element-plus'
import {
  getConversionBackShowApi,
  getConversionListApi,
  getConversionTypeApi,
  saveConversionApi
} from '@/api/inventory'
import { sumItem } from '@/utils'
import { ElMessage } from 'element-plus'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useAppStore } from '@/store/modules/app'

const { t } = useI18n()
const { go, push } = useRouter()
const { query } = useRoute()

// 移动端检测
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

let loading = ref<boolean>(false)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  cname: '',
  warehouse_value: '',
  intoWarehouse: '',
  arrival_date: '',
  initial_qty: '',
  convertible_qty: '',
  conversionType: '',
  arrivalDate: '',
  code: '',
  is_futures_value: '',
  inbound_batch: '',
  available_qty: '',
  lock_qty: '',
  conversionsNum: '',
  arrival_batch: ''
})
const rules = ref<FormRules>({
  conversionType: [
    {
      required: true,
      message: t('inventory.conversion.conversionTypeValidation'),
      trigger: 'change'
    }
  ],
  intoWarehouse: [
    {
      required: true,
      message: t('inventory.conversion.intoWarehouseValidation'),
      trigger: 'change'
    }
  ],
  arrivalDate: [
    { required: true, message: t('inventory.conversion.arrivalDateValidation'), trigger: 'change' }
  ],
  conversionsNum: [
    {
      required: true,
      trigger: ['change', 'blur'],
      validator: (rule: Record<string, any>, value: string, callback: Function) => {
        if (!value) {
          callback(new Error(t('inventory.conversion.conversionsNumValidation')))
        } else {
          if (parseFloat(value) <= parseFloat(form.value.convertible_qty)) {
            callback()
          } else {
            callback(new Error(t('inventory.conversion.conversionsNumValidationMsg')))
          }
        }
      }
    }
  ],
  arrival_batch: {
    required: true,
    trigger: ['blur'],
    validator: (rule: Record<string, any>, value: string, callback: Function) => {
      if (!value) {
        callback(new Error(t('purchase.batchValMsg')))
      } else {
        if (/^[A-Za-z0-9-_]{6,}$/.test(value)) {
          callback()
        } else {
          callback(new Error(t('purchase.batchValidation')))
        }
      }
    }
  }
})

const tableData = ref<Array<Record<string, any>>>([])
const multipleTable = ref<TableInstance>()
const multipleSelection = ref<Array<Record<string, any>>>([])
const packMultipleSelection = ref<Array<Record<string, any>>>([])
const conversionTypeOptions = ref<Array<Record<string, any>>>([])
const { emit } = useEventBus()
const has_first_warehouse = ref<number>()

//处理可选日期范围
const disabledDate = (time: Date) => time.getTime() < Date.now()

//选择转入仓库后重新查询底部列表数据
const handleChangeIntoWarehouse = async (e: number) => {
  const resp = await getConversionListApi({
    id: query.id as string,
    currentWId: form.value.wid,
    transferInWId: e
  })
  tableData.value = resp.data

  nextTick(() => {
    multipleTable.value?.toggleAllSelection()
  })
}
//勾选列表
const handleSelectionChange = (val: any[]) => {
  packMultipleSelection.value = val
  const filterQTY = val.flatMap((item: Record<string, any>) => [parseFloat(item.num)])
  if (parseFloat(sumItem(filterQTY)) > parseFloat(form.value.conversionsNum))
    return ElMessage.warning(t('inventory.conversion.noticeMsg'))

  multipleSelection.value = val.flatMap((item: Record<string, any>) => [
    { id: item.order_id, type: item.type, num: item.num }
  ])
  if (!multipleSelection.value.length)
    nextTick(() => {
      multipleTable.value?.clearSelection()
    })
}

//提交表单
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      //反向校验勾选数量是否大于转换数量
      const filterQTY = packMultipleSelection.value.flatMap((item: Record<string, any>) => [
        parseFloat(item.num)
      ])
      if (parseFloat(sumItem(filterQTY)) > parseFloat(form.value.conversionsNum))
        return ElMessage.warning(t('inventory.conversion.noticeMsg'))
      const params = {
        id: parseInt(query.id as string),
        futures: form.value.conversionType,
        arrival_date: form.value.arrivalDate,
        convertible_qty: parseFloat(form.value.conversionsNum),
        intoWarehouse: form.value.intoWarehouse,
        arrival_batch: form.value.arrival_batch,
        list: multipleSelection.value
      }
      const resp = await saveConversionApi(params)
      if (resp.code === 0) {
        ElMessage.warning(t('inventory.conversion.successNoticeMsg'))
        emit('getInventoryList', 'add')
        await push('/warehouse/inventory-management')
      }
    }
  })
}
const initialize = async () => {
  const res = await getConversionTypeApi(query.id as string)
  conversionTypeOptions.value = res.data
  const resp = await getConversionBackShowApi(query.id as string)
  has_first_warehouse.value = resp.data.has_first_warehouse
  console.log(has_first_warehouse.value, 9888)
  form.value = resp.data
  form.value.conversionType =
    conversionTypeOptions.value.find((item: Record<string, any>) => item.selected)?.value ?? ''
  const conversionResp = await getConversionListApi({
    id: query.id as string,
    currentWId: resp.data.wid
  })
  tableData.value = conversionResp.data

  nextTick(() => {
    multipleTable.value?.toggleAllSelection()
  })
}
const handleJumpToOrder = (row: Record<string, any>) => {
  let path =
    row?.order_type === 'order'
      ? '/order/order-management/detail'
      : '/order/wholesal-order-management/detail'
  push({
    path: path,
    query: { id: row?.order_id }
  })
}
onMounted(() => {
  initialize()
})
</script>
<style lang="less" scoped>
// 移动端样式
@media (width <= 968px) {
  .mobile-conversion-wrap {
    :deep(.content-detail-wrap) {
      padding: 12px;
    }
  }

  .mobile-form-layout {
    .el-form-item {
      margin-bottom: 16px;

      .el-form-item__label {
        width: 110px !important;
        text-align: left;
      }

      .el-form-item__content {
        margin-left: 110px !important;
      }
    }
  }
}
</style>
